
<template>
  <div style="overflow: auto">
    <el-card class="box-card" style=" height: 800px; overflow: auto">
      <el-col :span="12"><div class="grid-content bg-purple">
        <el-card class="box-card" >
          <div slot="header" class="clearfix">
            <span>摄像机信息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="dialogVisible = true">新增摄像机</el-button>
          </div>
          <el-table
            :data="CameratableData"
            style="width: 100%"
            border
           >
            <el-table-column
              prop="id"
              v-if="false"
              label="id"
              width="50">
            </el-table-column>
            <el-table-column
              prop="name"
              label="摄像机名称"
              width="150">
            </el-table-column>
            <el-table-column
              prop="url"
              label="摄像机地址"
              :show-overflow-tooltip="true"
              width="150">
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">

              <el-button type="primary" round icon="el-icon-video-play" circle @click="connect(scope.row)" ></el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="DeleteCamera(scope.row.id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </div></el-col>
      <el-col :span="12"><div class="grid-content bg-purple">
        <el-card class="box-card" style="overflow: auto">
          <div slot="header" class="clearfix">
            <span>画面预览</span>
              <el-button style="float: right; padding: 3px 3px" type="text" @click="cutPicture">
                立即截图
              </el-button>
            <el-button style="float: right; padding: 3px 0px" type="text" @click="drawerframe=true">
              隔帧截图
            </el-button>
            <el-button style="float: right; padding: 3px 0px" type="text" @click="drawersecondes=true">
              隔秒截图
            </el-button>
          </div>
          <div >
            <video controls id="videoId"  ref="video" style="width: 100%;height: 500px" poster="https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg" />
          </div>
          <el-divider content-position="center">截图预览</el-divider>
          <el-carousel :interval="4000" type="card" height="200px">
            <el-carousel-item v-for="(item) in carouselList" :key="item">
<!--              <h3 class="medium">{{ k }}</h3>-->
              <div class="demo-image__preview">
                <el-image
                  style="width: 400px; height: 200px"
                  :src="item"
                  :preview-src-list="carouselList">
                </el-image>
              </div>
            </el-carousel-item>
          </el-carousel>
          <div style="overflow: auto">
            <canvas id="myCanvas" ref="canvas" width="200px" height="200px" v-show="false"></canvas>
          </div>

        </el-card>
      </div></el-col>
    </el-card>
    <el-dialog
      title="新增摄像机"
      :visible.sync="dialogVisible"
      width="30%"
     >
      <el-form label-position="left" label-width="80px" :model="formLabelAlign">
        <el-form-item label="名称">
          <el-input v-model="formLabelAlign.name"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="formLabelAlign.url"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="newCamerapost2backEnd">确 定</el-button>
  </span>
    </el-dialog>

    <el-drawer
      title="隔帧取图"
      :visible.sync="drawerframe"
      direction="rtl"
      size="16%"
    >
      <div style="margin-left: 20px">
        <el-form label-position="top"  >
          <el-form-item label="每隔几帧截一张图？"
          >
            <el-input v-model="FrameInterval" size="mini" style="width: 60px"></el-input>  帧
          </el-form-item>
          <el-form-item label="共截图几张？">
            <el-input v-model="FrameCount" size="mini" style="width: 60px"></el-input>  张
          </el-form-item>
          <el-button
            @click="startScreenbyFrame"
            >开始截图</el-button>
        </el-form>
      </div>

    </el-drawer>
    <el-drawer
      title="隔秒取图"
      :visible.sync="drawersecondes"
      direction="rtl"
      size="16%"
    >
      <div style="margin-left: 20px">
        <el-form label-position="top"  >
          <el-form-item label="每隔几秒截一张图？"
          >
            <el-input v-model="SecondesInterval" size="mini" style="width: 60px;"></el-input>  秒
          </el-form-item>
          <el-form-item label="共截图几张？">
            <el-input v-model="SecondesFrameCount" size="mini" style="width: 60px"></el-input>  张
          </el-form-item>
          <el-button @click="startScreenbySecondes">开始截图</el-button>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import './webrtcstreamer.js'
import { GetList, AddObj, DelObj, UploadShotScreen, UploadShotScreenSrc } from './api'
export default {
  name: 'CameraManagement',
  data () {
    return {
      CameratableData: [],
      dialogVisible: false,
      formLabelAlign: {
        is_deleted: false,
        name: '',
        url: '',
        cameratype: 0,
        params1: '',
        params2: {},
        params3: '',
        creator: 1

      },
      webRtcServer: null,
      rtsp: '',
      imgSrc: '',
      videoData: {},
      drawerframe: false,
      drawersecondes: false,
      frameCount: 0,
      SecondesFrameCount: 3,
      SecondesInterval: 1,
      FrameCount: 3,
      FrameInterval: 1,
      dataURLArr: [],
      loading: null, // 上传图片等待
      carouselList: []
    }
  },
  created () {
    this.getCameraList()
  },
  mounted () {

  },
  beforeDestroy () {
    if (this.webRtcServer !== null) {
      this.webRtcServer.disconnect()
    }
    clearInterval(this.screenshotintervalbySecondes)
    clearInterval(this.screenshotIntervalbyFrame)
  },
  methods: {
    async startSend () {
      this.FrameCount = 3
      this.FrameInterval = 1
      const screenshotsdir = {
        dept_belong_id: 1,
        is_deleted: false,
        name: 'screenshots',
        src: this.dataURLArr,
        dir: Date.now(),
        creator: 1
      }
      await UploadShotScreenSrc(screenshotsdir)
      const screenshotsdb = {
        dept_belong_id: 1,
        is_deleted: false,
        name: 'screenshots',
        src: screenshotsdir.src.length,
        dir: screenshotsdir.dir,
        creator: 1
      }
      await UploadShotScreen(screenshotsdb)
      this.dataURLArr = []
      this.loading.close()
      this.$message.success(`已上传截图${this.frameCount}张`)
      this.frameCount = 0
    },
    startScreenbySecondes () {
      this.screenshotintervalbySecondes = setInterval(this.screenshotbySecondes, this.SecondesInterval * 1000)
      this.drawersecondes = false
      this.loading = this.$loading({
        lock: true,
        text: '正在截图...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    async screenshotbySecondes () {
      const video = this.$refs.video
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')

      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      // ctx.globalCompositeOperation = 'source-atop'
      ctx.drawImage(video, 0, 0)
      const dataURL = canvas.toDataURL()
      this.dataURLArr.push(dataURL)
      this.frameCount++
      this.carouselList = this.dataURLArr
      if (this.frameCount == this.SecondesFrameCount) {
        clearInterval(this.screenshotintervalbySecondes)
        console.log('已截图', this.frameCount)
        console.log(this.dataURLArr)
        this.$alert('已完成截取,是否上传?', '上传', {
          confirmButtonText: '确定',
          callback: action => {
            if (action === 'confirm') {
              this.startSend()
            } else {
              this.dataURLArr = []
              this.frameCount = 0
              this.loading.close()
              this.$message({
                type: 'info',
                message: '取消了上传'
              })
            }
          }
        })
      }
    },
    startScreenbyFrame () {
      this.screenshotIntervalbyFrame = setInterval(this.screenshotbyFrame, (1000 / 30) * this.FrameInterval) // 30 fps
      this.drawerframe = false
      this.loading = this.$loading({
        lock: true,
        text: '正在截图...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    async screenshotbyFrame () {
      const video = this.$refs.video
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')

      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      // ctx.globalCompositeOperation = 'source-atop'
      ctx.drawImage(video, 0, 0)
      const dataURL = canvas.toDataURL()
      this.dataURLArr.push(dataURL)
      this.frameCount++
      this.carouselList = this.dataURLArr
      if (this.frameCount == this.FrameCount) {
        clearInterval(this.screenshotIntervalbyFrame)
        console.log('已截图', this.frameCount)
        console.log(this.dataURLArr)
        this.$alert('已完成截取,是否上传?', '上传', {
          confirmButtonText: '确定',
          callback: action => {
            if (action === 'confirm') {
              this.startSend()
            } else {
              this.dataURLArr = []
              this.frameCount = 0
              this.loading.close()
              this.$message({
                type: 'info',
                message: '取消了上传'
              })
            }
          }
        })
      }
    },
    cutPicture () {
      var v = document.querySelector('video')
      const canvas = document.getElementById('myCanvas')
      var ctx = canvas.getContext('2d')
      canvas.width = v.videoWidth
      canvas.height = v.videoHeight
      ctx.drawImage(v, 0, 0)
      const dataImg = new Image()
      dataImg.src = canvas.toDataURL('image/jpeg')
      this.dataURLArr.push(dataImg.src)
      this.carouselList = this.dataURLArr

      this.$alert('已完成截取,是否上传?', '上传', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') {
            const screenshotsdir = {
              dept_belong_id: 1,
              is_deleted: false,
              name: 'screenshots',
              src: this.dataURLArr,
              dir: Date.now(),
              creator: 1
            }
            UploadShotScreenSrc(screenshotsdir)
            const screenshotsdb = {
              dept_belong_id: 1,
              is_deleted: false,
              name: 'screenshots',
              src: screenshotsdir.src.length,
              dir: screenshotsdir.dir,
              creator: 1
            }
            UploadShotScreen(screenshotsdb)
            this.$message.success('已上传截图1张')
          } else {
            this.loading.close()
            this.$message({
              type: 'info',
              message: '取消了上传'
            })
          }
        }
      })
      this.dataURLArr = []
    },
    connect (e) {
      // eslint-disable-next-line no-undef
      if (this.webRtcServer !== null) {
        this.webRtcServer.disconnect()
      }
      this.rtsp = e.url
      // eslint-disable-next-line no-undef
      this.webRtcServer = new WebRtcStreamer('videoId', 'http://127.0.0.1:8888')
      this.webRtcServer.connect(this.rtsp)
    },
    async getCameraList () {
      const res = await GetList()
      this.CameratableData = res.data.data
    },
    async newCamerapost2backEnd () {
      const res = await AddObj(this.formLabelAlign)
      console.log(res)
      this.dialogVisible = false
      this.formLabelAlign.name = ''
      this.formLabelAlign.url = ''
      this.getCameraList()
    },
    async DeleteCamera (id) {
      await DelObj(id)
      this.getCameraList()
    }

  }

}
</script>
<style  scoped>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

</style>
